package com.pearl.jacksonspringboot.demo.mask;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;

/**
 * @author TD
 * @version 1.0
 * @date 2024/4/23
 */
public class MaskFromXToYJsonSerializer extends StdSerializer<String> implements ContextualSerializer {

    private int from;

    private int to;

    private String replaceChar;

    public MaskFromXToYJsonSerializer(Class<String> t, int from, int to, String replaceChar) {
        super(t);
        this.from = from;
        this.to = to;
        this.replaceChar = replaceChar;
    }

    public MaskFromXToYJsonSerializer() {
        super(String.class);
    }

    /**
     * 序列化
     */
    @Override
    public void serialize(String str, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        // 1. 校验
        if (this.from >= this.to) {
            throw new RuntimeException("起始位置不能大于等于结束位置");
        }
        if (StrUtil.isEmpty(this.replaceChar)) {
            throw new RuntimeException("替换字符不能为空");
        }
        // 2. 序列化
        if (StrUtil.isEmpty(str)) {
            // 为空
            jsonGenerator.writeString("");
        } else if (str.length() <= this.from) {
            // 字符长度小于开始位置
            jsonGenerator.writeString(str);
        } else {
            // 脱敏写出
            char[] chars = str.toCharArray();
            int i = this.from;
            for (int minLength = Math.min(this.to, chars.length - 1); i <= minLength; ++i) {
                chars[i] = this.replaceChar.charAt(0);
            }
            jsonGenerator.writeString(new String(chars));
        }
    }

    /**
     * 根据字段注解，返回序列化器，仅在在第一次序列化时调用
     */
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializers, BeanProperty property) throws JsonMappingException {
        // 1. 属性为 Null
        if (property == null) {
            return serializers.findNullValueSerializer(null);
        }
        // 2. 属性的类型
        Class<?> rawClass = property.getType().getRawClass();
        if (CharSequence.class.isAssignableFrom(rawClass)) {
            // 3. 字符串类型，返回脱敏序列化器
            MaskFromXToYMask annotation = property.getAnnotation(MaskFromXToYMask.class);
            if (annotation == null) {
                annotation = property.getContextAnnotation(MaskFromXToYMask.class);
            }
            if (annotation != null) {
                return new MaskFromXToYJsonSerializer(String.class, annotation.from(), annotation.to(), annotation.replaceChar());
            }

        }
        return serializers.findValueSerializer(property.getType(), property);
    }
}